package com.gitee.qdbp.base.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 在TagSupport中获取request.getRequestURI()时获取到的是forword之后的jsp路径<br>
 * 如http://localhost:8000/xxx/映射到/WEB-INF/home/index.jsp<br>
 * 在TagSupport中RequestURI = /xxx/WEB-INF/home/index.jsp而不是浏览器中原始的请求路径<br>
 * 只好加一个过滤器, 在跳转到jsp之前将RequestURI/RequestURL参数记录下来
 *
 * @author zhaohuihua
 * @version 181026
 */
public final class SaveRequestDataFilter implements Filter {
    // url = http://localhost:8000/xxx/
    // ServletPath = /WEB-INF/home/index.jsp
    // RequestURI = /xxx/WEB-INF/home/index.jsp
    // RequestURL = http://localhost:8000/xxx/WEB-INF/home/index.jsp

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
            String message = "Doesn't support non-HTTP request or response.";
            throw new ServletException(message);
        }

        // Safe to downcast at this point.
        HttpServletRequest req = (HttpServletRequest) request;
        req.setAttribute("OriginalServletPath", req.getServletPath());
        req.setAttribute("OriginalRequestURI", req.getRequestURI());
        req.setAttribute("OriginalRequestURL", req.getRequestURL().toString());

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

}
